package com.zhao.filter;


import com.zhao.bean.Employee;
import com.zhao.bean.User;
import com.zhao.config.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取当前请求地址进行判断是否需要拦截
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        //对请求地址进行判断是否进行拦截 | 放行
        if (uri.contains("login") || uri.contains("logout")
                || uri.endsWith(".css") || uri.endsWith(".js")
                || uri.endsWith(".png") || uri.endsWith(".jpg")
                || uri.contains("plugins") || uri.contains("ico") || uri.contains("upload")
                || uri.contains("sendMsg")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //判断是否已经登录，如果有值代表已经登录，就放行，return结束方法
        Employee employee = (Employee) req.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.set(employee.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        //判断用户端是否已经登录，如果有值代表已经登录，就放行，return结束方法
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.set(user.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //到这说明没登录过，重定向到登录界面
        //如果是登录者在用户端，判断关键字front后重定向
        if (uri.contains("front")) {
            resp.sendRedirect("/front/page/login.html");
        } else {
            //当前面都没有进行方行代码走到这里时，就拦截进行重定向，让页面返回登录页面
            resp.sendRedirect("/backend/page/login/login.html");

        }
    }
}
